package com.py.credit.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.ServiceException;
import com.py.credit.dao.CustomOuterInterfaceDao;
import com.py.credit.entity.CustomOuterInterface;
import com.py.credit.service.CustomOuterInterfaceService;
import com.py.credit.utils.SQLBuilder;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;

import freemarker.template.utility.StringUtil;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CustomOuterInterfaceServiceImpl implements CustomOuterInterfaceService {

    @Autowired
    private CustomOuterInterfaceDao customOuterInterfaceDao;

    @Override
    public List<Map<String, Object>> getByConditionForPage(List<String> showColumns, String[] additionalColumns, String condition, Page page) {
        if (CollectionUtils.isEmpty(showColumns)) {
            throw new ServiceException("至少选择一列");
        }
        List<String> conditions = SQLBuilder.createConditionSql(condition);
        return customOuterInterfaceDao.selectByConditionForPage(showColumns, additionalColumns, conditions, page);
    }

    @Override
    public void add(CustomOuterInterface record) {
        record.setCode(UuidUtil.getInstance().getUUid());
        customOuterInterfaceDao.insertSelective(record);
    }

    @Override
    public CustomOuterInterface getRecordById(int id) {
        return customOuterInterfaceDao.selectByPrimaryKey(id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, Object>> execute(String condition, String sql,String name) {
        Map<String, String> parseObject;
        try {
        	StringBuilder builder = new StringBuilder(sql);
            parseObject = JSONObject.parseObject(condition, Map.class);
            //获取接口中的业务数据
            String busParams = parseObject.get("params");
            Map<String, String> paramMap = new HashMap<String, String>();
          if(!StringUtils.isEmpty(busParams)) {
        	  paramMap = JSONObject.parseObject(busParams, Map.class); 
          
            buildSql(paramMap, builder);
          }
          if(name.equals("xzxk_code")) {
        	  builder.append(" order by XK_JDRQ desc "); 
          }else if(name.equals("xzcf_code")){
        	  builder.append(" order by CF_JDRQ desc "); 
          }else if(name.equals("tyshxydm_code")){
        	  builder.append(" or A000002  like concat( '%', '").append(paramMap.get("A000001")).append("' ,'%')");;
          }
            builder.append(" limit #{pageNo},#{pageSize};");
            
            parseObject.put("sql", builder.toString());
        } catch (Exception e) {
            throw new ServiceException("condition 参数格式非法");
        }
        return customOuterInterfaceDao.executeDynamicSql(parseObject);
    }
   
    /**
     * 功能描述:拼接sql查询条件
     *
     * @param paramMap 参数map
     * @param sql      sql
     * @author YaoS
     * @date 2020/4/23 20:13
     */
    public void buildSql(Map<String, String> paramMap, StringBuilder sql) {
    	String value = "";
        if (!Collections.isEmpty(paramMap)) {
            for (String key : paramMap.keySet()) {
            	if(paramMap.get(key)!=null&&!paramMap.get(key).equals("")) {
            			if(paramMap.get(key).contains("~")) {
            				value=	paramMap.get(key).trim();
            				sql.append(" and date_format(").append(key).append(",'%Y-%m-%d')").append(" >= '").append(value.substring(0, value.lastIndexOf("~"))).
            				append("' and date_format(").append(key).append(",'%Y-%m-%d')").append("<='").append(value.substring(value.lastIndexOf("~")+1,value.length())).append("' ");
            			}else {
            				 sql.append(" and ").append(key).append(" like concat( '%', '")
                             .append(paramMap.get(key)).append("' ,'%')");
            			}
            		
            		
            	}
               
            }
        }
    }

    @Override
    public CustomOuterInterface getRecordByCode(String interfaceCode) {
        return customOuterInterfaceDao.selectByByCode(interfaceCode);
    }

    @Override
    public void update(CustomOuterInterface customOuterInterface) {
    	 StringBuilder listSql = new StringBuilder();
         String tablename = "t_"+customOuterInterface.getTablename();
         List<Map<String, String>> list = customOuterInterface.getCloums();
         listSql.append(" select  m.dept_id as deptId,l.OFFICE_NAME as deptName, ");
         StringBuilder detailSql = new StringBuilder();
         detailSql.append(" select ");
         for (Map<String, String> stringStringMap : list) {
             for (String k : stringStringMap.keySet()) {
                 if ("1".equals(stringStringMap.get(k))) {
                     k = "IFNULL( " + k + " , '' ) as " + k;
                 } else {
                     k = " '' as " + k;
                 }
                 listSql.append(k).append(",");
                 detailSql.append(k).append(",");
             }
         }
         listSql.deleteCharAt(listSql.length() - 1);
         detailSql.deleteCharAt(detailSql.length() - 1);
         detailSql.append(",record_id, '").append(tablename).append("' as tablename ").append("  from  ").append("t_").append(customOuterInterface.getTablename()).append(" where tybm =#{tybm};");
         listSql.append(",record_id, '").append(tablename).append("' as tablename ").append(" from ").append("t_").append(customOuterInterface.getTablename()).append(" n join t_ex_batch_log m on n.batch_Id=m.batch_id left join t_sys_office l on m.dept_id=l.id ").append(" where 1=1 ");
         if(customOuterInterface.getDescription().equals("行政处罚")) {
      	   listSql.append(" and CF_GSJZQ>now() and n.status !='F'");
         }
         customOuterInterface.setListSql(listSql.toString());
         customOuterInterface.setDetailSql(detailSql.toString());  
        customOuterInterfaceDao.updateByPrimaryKeySelective(customOuterInterface);
    }

    @Override
    public List<Map<String, String>> getTableResource() {
        return customOuterInterfaceDao.getTableResource();
    }

    @Override
    public List<Map<String, String>> getTableColums(String tableId) {
        return customOuterInterfaceDao.getTableColums(tableId);
    }

    @Override
    public void addSgs(CustomOuterInterface customOuterInterface) {
        String cord = UuidUtil.getInstance().getUUid();
        customOuterInterface.setCode(cord);
        StringBuilder listSql = new StringBuilder();
        String tablename = "t_"+customOuterInterface.getTablename();
        List<Map<String, String>> list = customOuterInterface.getCloums();
        listSql.append(" select  m.dept_id as deptId,l.OFFICE_NAME as deptName, ");
        StringBuilder detailSql = new StringBuilder();
        detailSql.append(" select ");
        for (Map<String, String> stringStringMap : list) {
            for (String k : stringStringMap.keySet()) {
                if ("1".equals(stringStringMap.get(k))) {
                	if(customOuterInterfaceDao.checkMetricType(k).toString().contains("time")||customOuterInterfaceDao.checkMetricType(k).toString().contains("date")) {
                		k = "IFNULL(DATE_FORMAT( " + k + ",\"%Y-%m-%d\") , '' ) as " + k;
                	}else {
                		k = "IFNULL( " + k + " , '' ) as " + k;
                	}
                    
                } else {
                    k = " '' as " + k;
                }
                listSql.append(k).append(",");
                detailSql.append(k).append(",");
            }
        }
        listSql.deleteCharAt(listSql.length() - 1);
        detailSql.deleteCharAt(detailSql.length() - 1);
        detailSql.append(",record_id, '").append(tablename).append("' as tablename ").append("  from  ").append("t_").append(customOuterInterface.getTablename()).append(" where tybm =#{tybm};");
        listSql.append(",record_id, '").append(tablename).append("' as tablename ").append(" from ").append("t_").append(customOuterInterface.getTablename()).append(" n join t_ex_batch_log m on n.batch_Id=m.batch_id left join t_sys_office l on m.dept_id=l.id ").append(" where 1=1 ");
       if(customOuterInterface.getDescription().equals("行政处罚")) {
    	   listSql.append(" and CF_GSJZQ>now() and n.status !='F'");
       }
        customOuterInterface.setListSql(listSql.toString());
        customOuterInterface.setDetailSql(detailSql.toString());
        customOuterInterfaceDao.insertSgsSelective(customOuterInterface);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Integer executeCount(String condition, String sql) {
        Map<String, String> parseObject;
        StringBuilder builder = new StringBuilder(sql);
        try {
            parseObject = JSONObject.parseObject(condition, Map.class);
            //获取接口中的业务数据
            String busParams = parseObject.get("params");
            Map<String, String> paramMap = JSONObject.parseObject(busParams, Map.class);
            buildSql(paramMap, builder);
        } catch (Exception e) {
            throw new ServiceException("condition 参数格式非法");
        }
        return customOuterInterfaceDao.executeCountSql(builder.toString());
    }

  
}
